<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="设备名称" style="width: 300px;">
          <el-input v-model="searchForm.name" placeholder="设备名称"></el-input>
        </el-form-item>
        <el-form-item label="设备型号" style="width: 300px;">
          <el-input v-model="searchForm.model" placeholder="设备型号"></el-input>
        </el-form-item>
        <el-form-item label="状态" style="width: 300px;">
          <el-select v-model="searchForm.status" placeholder="状态">
            <el-option label="全部" value=""></el-option>
            <el-option label="启用" :value="1"></el-option>
            <el-option label="停用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="mt-2">
      <!-- 操作按钮 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <div>
            <el-button type="primary" @click="handleAdd" icon="Plus">新增</el-button>
            <el-button type="danger" @click="handleBatchDelete" :disabled="!multipleSelection.length" icon="Delete">
              批量删除
            </el-button>
          </div>
        </el-col>
        <el-col :span="12" class="flex-end">
          <right-toolbar :search="false" v-model:showSearch="showSearch" @queryTable="loadData"
            :columns="columns"></right-toolbar>
        </el-col>
      </el-row>

      <!-- 数据表格 -->
      <div class="table-container mt-2">
        <el-table :data="tableData" border style="width: 100%" v-loading="loading">
          <el-table-column prop="name" label="设备名称" align="center" v-if="columns[1].visible"></el-table-column>
          <el-table-column prop="model" label="设备型号" align="center" v-if="columns[2].visible"></el-table-column>
          <el-table-column prop="deviceCode" label="设备唯一编码" align="center" v-if="columns[2].visible"></el-table-column>
          <el-table-column prop="type" label="设备类型" align="center" v-if="columns[2].visible">
            <template #default="{ row }">
              <!-- deviceTypeList -->
              {{ deviceTypeList.find(item => item.value === row.type)?.label || '未知类型' }}
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" v-if="columns[4].visible">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.status === 1 ? '启用' : '停用' }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="vendor" label="厂家" align="center" v-if="columns[5].visible"></el-table-column>
          <el-table-column prop="powerType" label="供电策略" align="center" v-if="columns[6].visible"></el-table-column>
          <el-table-column prop="lastSeenAt" label="最后在线" align="center" v-if="columns[7].visible"></el-table-column>

          <el-table-column label="操作" align="center" fixed="right" v-if="columns[9].visible">
            <template #default="{ row }">
              <el-button size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%" :close-on-click-modal="false">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入设备名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备唯一编号" prop="deviceCode">
              <el-input v-model="formData.deviceCode" placeholder="请输入设备唯一编号"></el-input>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 做下拉列表 -->
            <el-form-item label="设备类型" prop="type">
              <el-select v-model="formData.type" placeholder="设备类型">
                <el-option v-for="item in deviceTypeList" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备型号" prop="model">
              <el-input v-model="formData.model" placeholder="请输入设备型号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="IP地址" prop="ipAddress">
              <el-input v-model="formData.ipAddress" placeholder="请输入IP地址"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="端口号" prop="port">
              <el-input v-model="formData.port" placeholder="默认''"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="Modbus从站ID" prop="modbusSlaveId">
              <el-input v-model="formData.modbusSlaveId" placeholder="请输入从站ID"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="通讯协议" prop="protocol">
              <el-input v-model="formData.protocol" placeholder="请输入通讯协议"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择状态">
                <el-option label="启用" :value="1"></el-option>
                <el-option label="停用" :value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="厂家" prop="vendor">
              <el-input v-model="formData.vendor" placeholder="请输入厂家"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 做下拉列表 -->
            <el-form-item label="供电策略" prop="powerType">
              <el-select v-model="formData.powerType" placeholder="供电策略">
                <el-option v-for="item in powerStrategyList" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电池容量" prop="batteryCapacityMah">
              <el-input v-model="formData.batteryCapacityMah" placeholder="请输入电池容量"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="上报间隔" prop="reportIntervalSec">
              <el-input v-model="formData.reportIntervalSec" placeholder="请输入上报间隔"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="心跳间隔" prop="hbIntervalSec">
              <el-input v-model="formData.hbIntervalSec" placeholder="请输入心跳间隔"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="投运时间" prop="activatedAt">
              <el-input v-model="formData.activatedAt" placeholder="请输入投运时间"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="安装时间" prop="installAt">
              <el-input v-model="formData.installAt" placeholder="请输入安装时间"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属模板" prop="templateId">
              <el-select v-model="formData.templateId" placeholder="所属模板">
                <el-option v-for="item in templateList" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>

          </el-col>
          <el-col :span="12">

          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import { listDevice, getDeviceDetail, addDevice, updateDevice, deleteDevice, getTemplateList, getDeviceTypeList, getPowerStrategyList } from '@/api/park/device/businessFacilitiesInfo'

// 下拉列表相关
const templateList = ref()
const deviceTypeList = ref()
const powerStrategyList = ref()
const getDataList = async () => {
  const [templateRes, deviceTypeRes, powerStrategyRes] = await Promise.all([
    getTemplateList(),
    getDeviceTypeList(),
    getPowerStrategyList()
  ])
  templateList.value = templateRes.data.map(item => ({
    label: item.name,
    value: item.id
  }));
  deviceTypeList.value = deviceTypeRes.data.map(item => ({
    label: item.dictLabel,
    value: item.dictValue
  }));
  console.log(deviceTypeList.value);

  powerStrategyList.value = powerStrategyRes.data.map(item => ({
    label: item.dictLabel,
    value: item.dictValue
  }));
}


// 搜索表单
const searchForm = reactive({
  name: '',
  model: '',
  status: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 列显隐信息
const columns = ref([
  { key: 0, label: '设备ID', visible: true },
  { key: 1, label: '设备名称', visible: true },
  { key: 2, label: '设备型号', visible: true },
  { key: 3, label: '', visible: true },
  { key: 4, label: '状态', visible: true },
  { key: 5, label: '通讯协议', visible: true },
  { key: 6, label: 'IP地址', visible: true },
  { key: 7, label: '端口号', visible: true },
  { key: 8, label: 'Modbus从站ID', visible: true },
  { key: 9, label: '操作', visible: true }
])

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增设备')
const formRef = ref(null)
const formData = reactive({
  id: undefined,
  name: '',
  model: '',
  plantId: undefined,
  status: 1,
  protocol: '',
  ipAddress: '',
  port: "",
  modbusSlaveId: undefined,
  remark: ''
})

// 表单验证规则
const rules = reactive({
  name: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
  deviceCode: [{ required: true, message: '请输入设备唯一编码', trigger: 'blur' }],
  type: [{ required: true, message: '请选择设备类型', trigger: 'blur' }],
  port: [
    { pattern: /^\d+$/, message: '端口号必须为数字', trigger: 'blur' }
  ]
})

// 多选
const multipleSelection = ref([])
const showSearch = ref(true)

// 水厂选项（假设有获取水厂列表的接口）
const plantOptions = ref([
  { id: 1, name: '北京水厂' },
  { id: 2, name: '上海水厂' },
  { id: 3, name: '广州水厂' }
])

// 加载数据
const loadData = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    }
    const res = await listDevice(params)
    tableData.value = res.rows.map(item => ({
      ...item,
      plantName: plantOptions.value.find(p => p.id === item.plantId)?.name || '未知水厂'
    }))
    pagination.total = res.total
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  loadData()
}

// 多选变化
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  loadData()
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增设备'
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (row) => {
  dialogTitle.value = '编辑设备'
  try {
    const res = await getDeviceDetail(row.id)
    Object.assign(formData, res.data)
    dialogVisible.value = true
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.keys(formData).forEach(key => {
    formData[key] = key === 'status' ? 1 : key === 'port' ? '' : ''
  })
  formData.id = undefined
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    if (dialogTitle.value === '新增设备') {
      await addDevice(formData)
      ElMessage.success('新增成功')
    } else {
      await updateDevice(formData)
      ElMessage.success('更新成功')
    }

    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('表单提交失败:', error)
    if (error !== 'validate') {
      ElMessage.error('操作失败')
    }
  }
}

// 删除单个设备
const handleDelete = (id) => {
  ElMessageBox.confirm('确认删除该设备吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return deleteDevice([id])
  }).then(() => {
    ElMessage.success('删除成功')
    loadData()
  }).catch(() => { })
}

// 批量删除
const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }

  ElMessageBox.confirm(`确认删除选中的${multipleSelection.value.length}条记录吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const ids = multipleSelection.value.map(item => item.id)
    return deleteDevice(ids)
  }).then(() => {
    ElMessage.success('删除成功')
    loadData()
  }).catch(() => { })
}

// 初始化加载数据
onMounted(() => {
  loadData()
  getDataList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.mt-2 {
  margin-top: 20px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}

.flex-end {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>